const fs = require('fs')

const root = __dirname.slice(0,-6) //d:/web04327/node

const helper = {

    //文件上传
    upload: function (file) {

        //目标目录
        let dst = root + '/static/uploads'

        //新建文件名
        let date = new Date()
        let dt = date.getTime()

        //随机数
        let rand = parseInt(Math.random() * 1000)

        //新文件名
        let newTitle = dt + '' + rand

        //扩展名
        let nameArr = file.name.split(".")
        let extension = nameArr[nameArr.length - 1]

        //最终的文件路径
        let lastFile = dst + '/' + newTitle + '.' + extension //d:/web04327/node/static/uploads/x.dsss.xxx.jpg

        //上传到服务器
        //创建可读流
        let readStream = fs.createReadStream(file.path)

        //创建写入流
        let writeStream = fs.createWriteStream(lastFile)

        //管道
        if (readStream.pipe(writeStream)){
            return newTitle + '.' + extension
        } else {
            return;
        }

    },

    //删除文件
    delFile(filename){

        let path = root + '/static/uploads/' + filename

        //判断文件是否存在
        if (fs.existsSync(path)){

            //判断是文件还是目录
            if (fs.statSync(path).isDirectory()){
                return
            } else {
                try{
                    fs.unlinkSync(path)
                    return true
                } catch(err){
                    console.log(err);
                    return
                }
                
            }

        }

    }
}

module.exports = helper